//线性渐变材质类
import * as Cesium from "cesium";
function craeteImage(colorStops) {
    let c = document.createElement("canvas");
    c.height = 100;
    c.width = 200;
    let ctx = c.getContext("2d");
    let grd = ctx.createLinearGradient(200, 50, 0, 50);
    colorStops.forEach(item => {
        grd.addColorStop(item.stop, item.color);
    });
    ctx.fillStyle = grd;
    ctx.fillRect(0, 0, 200, 100);
    ctx.restore();
    return c.toDataURL("image/png").replace("image/png", "image/octet-stream");
}


export default class LinearGradientMaterialProperty {
    constructor(colorStops) {
        //颜色和占比 长度一致
        this._definitionChanged = new Cesium.Event();
        this._color = undefined;
        this._colorSubscription = undefined;
        colorStops = colorStops || [{
                stop: 0,
                color: "rgba(238,103,98,0.5)"
            },
            {
                stop: 1,
                color: "rgba(32,153,230,0.5)"
            }
        ]
        this.image = craeteImage(colorStops);
        this.color = Cesium.Color.RED.withAlpha(0.2);
    }
}
Object.defineProperties(LinearGradientMaterialProperty.prototype, {
    isConstant: {
        get: function() {
            return false;
        }
    },
    definitionChanged: {
        get: function() {
            return this._definitionChanged;
        }
    },
    color: Cesium.createPropertyDescriptor('color')
});
LinearGradientMaterialProperty.prototype.getType = function(time) {
    return 'LinearGradient';
}
LinearGradientMaterialProperty.prototype.getValue = function(time, result) {
    if (!Cesium.defined(result)) {
        result = {};
    }
    result.color = Cesium.Property.getValueOrClonedDefault(this._color, time, Cesium.Color.WHITE, result.color);
    result.image = this.image;
    return result;
}
LinearGradientMaterialProperty.prototype.equals = function(other) {
    return this === other ||
        (other instanceof LinearGradientMaterialProperty &&
            Cesium.Property.equals(this._color, other._color))
}

Cesium.Material.LinearGradientType = 'LinearGradient';
Cesium.Material.LinearGradientSource =
    "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
     czm_material material = czm_getDefaultMaterial(materialInput);\n\
     vec2 st = materialInput.st;\n\
     vec4 colorImage = texture(image, vec2(fract(st.t - time), st.t));\n\
     material.alpha = colorImage.a;\n\
     material.diffuse = colorImage.rgb * 1.3 ;\n\
     return material;\n\
 }";
Cesium.Material._materialCache.addMaterial(Cesium.Material.LinearGradientType, {
    fabric: {
        type: Cesium.Material.LinearGradientType,
        uniforms: {
            image: "",
            time: 0
        },
        source: Cesium.Material.LinearGradientSource
    },
    translucent: function(material) {
        return true;
    }
});
